Estadística y Manejo de Datos con R (EMDR) — Virtual

Gráficos avanzados con ggplot2

Gráficos avanzados

Gráficos avanzados: ggplot2

  • ggplot2 es un paquete de R para realizar gráficos modernos de alta calidad.

  • Utiliza una dinámica distinta a los gráficos básicos de R.

  • Es sintético: permite elaborar gráficos complejos con código sencillo.

  • Los Marcos de Datos son la estructura básica de ggplot2

  • Gráficos ¿más bonitos?

Gráficos avanzados: ggplot2

Gráficos avanzados: ggplot2

  • Ejemplo de The Economist

Gráficos avanzados: ggplot2

Gráficos avanzados: ggplot2

  • ggplot() recibe un data frame (marco de datos).

  • aes() recibe los componentes a graficar, junto con la variable agrupadora.

  • geom() especifica la capa que determina el tipo de gráfico.

Gráficos avanzados: ggplot2

  • ggplot2 debe estar instalado y cargado.
install.packages("ggplot2")
library(ggplot2)

Gráficos avanzados: geom_point()

  • Exploremos el conjunto de datos Orange
?Orange
head(Orange)
##   Tree  age circumference
## 1    1  118            30
## 2    1  484            58
## 3    1  664            87
## 4    1 1004           115
## 5    1 1231           120
## 6    1 1372           142

Gráficos avanzados: geom_point()

ggplot(Orange, aes(x = age, y = circumference)) + geom_point()

Gráficos avanzados: geom_point()

ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + 
  geom_point(shape = 1, size = 4)

Gráficos avanzados: geom_point()

ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + 
  geom_point(shape = 1) + geom_smooth(method = lm, se = FALSE)
## `geom_smooth()` using formula 'y ~ x'

Gráficos avanzados: geom_point()

ggplot(Orange, aes(x = age, y = circumference, shape = Tree)) + 
  geom_point(size = 2)

Gráficos avanzados: geom_point()

ggplot(Orange, aes(x = age, y = circumference, shape = Tree)) + 
  geom_point() + scale_shape_manual(values = c(1:5))

Gráficos avanzados: geom_line()

  • Exploremos el conjunto de datos ToothGrowth. Mantengamos en mente para el siguiente Tema, la codificación de la función std.
library(dplyr)
library(magrittr)
?ToothGrowth
head(ToothGrowth)
std <- function(x){sd(x)/ sqrt(length(x))}
TG <- ToothGrowth %>% 
  group_by(dose, supp) %>% 
  summarize(ml = mean(len), sle = std(len))
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5

Gráficos avanzados: geom_line()

ggplot(TG, aes(x = dose, y = ml, group = supp)) + 
  geom_line()

Gráficos avanzados: geom_line()

ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) +
  geom_line() + geom_point()

Gráficos avanzados: geom_line()

 ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) +
  geom_line() + geom_point() + 
  geom_errorbar(aes(ymax = ml + sle, ymin = ml - sle), width = 0)

Gráficos avanzados: geom_line()

ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) + 
  geom_line() + geom_errorbar(aes(ymax = ml+sle, ymin = ml-sle), width = 0) +
  xlab("Dose (ml)") + ylab("Length (mm)") + ggtitle("Length vs Dose")

Gráficos avanzados: geom_bar()

  • Exploremos el conjunto de datos PlantGrowth.
library(dplyr)
library(magrittr)
?PlantGrowth
head(PlantGrowth)
mPG <- PlantGrowth %>% 
  group_by(group) %>%
  summarize(mw = mean(weight), sdw = sd(weight))
##   weight group
## 1   4.17  ctrl
## 2   5.58  ctrl
## 3   5.18  ctrl
## 4   6.11  ctrl
## 5   4.50  ctrl
## 6   4.61  ctrl

Gráficos avanzados: geom_bar()

ggplot(mPG, aes(x= group, y= mw)) + geom_bar(stat = "identity")

Gráficos avanzados: geom_bar()

ggplot(data = mPG, aes(x = group, y = mw, fill = group)) + 
  geom_bar(stat = "identity", color = "black") + 
  geom_errorbar(aes(ymax = mw + sdw, ymin = mw - sdw), width = 0.25)

Gráficos avanzados: geom_histogram()

  • Exploremos el conjunto de datos Seatbelts.
?Seatbelts
SB.df <- as.data.frame(Seatbelts)
head(SB.df)
##   DriversKilled drivers front rear   kms PetrolPrice VanKilled law
## 1           107    1687   867  269  9059   0.1029718        12   0
## 2            97    1508   825  265  7685   0.1023630         6   0
## 3           102    1507   806  319  9963   0.1020625        12   0
## 4            87    1385   814  407 10955   0.1008733         8   0
## 5           119    1632   991  454 11823   0.1010197        10   0
## 6           106    1511   945  427 12391   0.1005812        13   0

Gráficos avanzados: geom_histogram()

ggplot(SB.df, aes(x = DriversKilled)) + 
  geom_histogram(binwidth = 10, color = "black", fill = "white")

Gráficos avanzados: geom_histogram()

ggplot(SB.df, aes(x = DriversKilled, fill = as.factor(law))) +
  geom_histogram(binwidth = 10, alpha =.5, position = "identity")

Gráficos avanzados: otras funciones

  • Exploremos y grafiquemos el conjunto de datos OrchardSprays.
?OrchardSprays
head(OrchardSprays)
p <- ggplot(data = OrchardSprays, aes(x = factor(treatment), y = rowpos)) + 
    geom_point(aes(color = decrease), size = 16, shape = 15)

Gráficos avanzados: otras funciones

  • Añadir una escala con scale_color_gradient()
p <- p + scale_color_gradient(low = "red", high = "yellow", "Efecto",
              with(OrchardSprays, c(min(decrease), mean(decrease),
              max(decrease))), labels = c("Alto","Medio","Bajo"))
p

Gráficos avanzados: otras funciones

  • Temas predeterminados.
bp <- ggplot(data = PlantGrowth, aes(x = group, y = weight, fill = group)) +
  geom_boxplot() + theme_bw()

Gráficos avanzados: otras funciones

  • Añade un título.
bp <- bp + ggtitle("Plant growth")

Gráficos avanzados: otras funciones

  • Añade un título de dos líneas
bp <- bp + ggtitle("Plant growth with \n different treatments")

Gráficos avanzados: otras funciones

  • Cambia las tickmarks:
bp + xlab("Group") + ylab("Weight") + 
  scale_x_discrete(labels = 
                     c("ctrl" = "Control","trt1" = "Treatment1","trt2" = "Treatment2"))

Gráficos avanzados: otras funciones

  • Título y colores de la leyenda
bp + scale_fill_brewer(name ="Experimental\nCondition", palette = "Greens")

Gráficos avanzados: facet_grid

  • Gráficos múltiples
data(tips, package="reshape2")
sp <- ggplot(tips, aes(x= total_bill, y= tip/total_bill)) + geom_point(shape = 1)

Gráficos avanzados: facet_grid

  • Gráficos múltiples, por sex (horizontal)
sp + facet_grid(sex ~ .) 

Gráficos avanzados: facet_grid

  • Gráficos múltiples, por sex (vertical).
sp + facet_grid(. ~ sex)

Gráficos avanzados: facet_grid

  • Gáficos múltiples, por sex y day.
sp + facet_grid(sex ~ day)

Gráficos avanzados: facet_wrap

  • Gráficos múltiples especificando número de columnas.
sp + facet_wrap(~ day, ncol = 2) # intenta 3 y 5

Gráficos avanzados: otras funciones

  • Guardamos con ggsave.
ggsave(file ="myplot.pdf")

ggsave(file ="myplot.png") # Soporte png

ggsave(myplot, file ="myplot.pdf") # Usando el objeto

ggsave(myplot, file ="myplot.pdf", width = 4, height = 4) # Especificando el tamaño

Gráficos avanzados: Ejercicios

  • Crea el siguiente gráfico con el conjunto de datos diamonds.
?diamonds
head(diamonds)

Gráficos avanzados: Ejercicios

  • Solución
    • Disponible después de la fecha de entrega.

Otros paquetes gráficos

Otros paquetes para graficar

Otros paquetes para graficar

library(plotly)
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
# Resultado interactivo, mueve el cursor sobre el gráfico.

Otros paquetes para graficar

Otros paquetes para graficar

library(lattice)
xyplot(lat ~ long | cut(depth, 2), data = quakes, outer = T, grid = T)

Otros paquetes para graficar

library(lattice)
heatmap(matrix(DNase$density, ncol = 11))

Y más paquetes para graficar

Y más paquetes para graficar

library(leaflet)
leaflet() %>% addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
# Resultado interactivo, mueve el cursor sobre el gráfico.

Y más paquetes para graficar

Y más paquetes para graficar

library(networkD3)
src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)
simpleNetwork(networkData) # Resultado interactivo, mueve el cursor sobre el gráfico.

Y más paquetes para graficar

Energy <- jsonlite::fromJSON("energy.json")
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source", 
              Target = "target", Value = "value", NodeID = "name", units = "TWh", 
              fontSize = 12, nodeWidth = 30)
# Resultado interactivo, mueve el cursor sobre el gráfico.

¿Gráficos básicos o ggplot2?

Licencia CC BY